package com.xtgg.device;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.xtgg.R;
import com.xtgg.baby.BabyBoundListActivity;
import com.xtgg.baby.BabyListActivity;
import com.xtgg.baby.VetifyCodeActivity;
import com.xtgg.login.LoginActivity;
import com.xtgg.main.MainActivity;
import com.xtgg.main.SingleImageShowActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class AddBabyActivity extends BaseActivity implements OnClickListener {
	int imgWidth = 0;

	String babyName = "";
	String babyNick = "";
	String babyBirth = "";
	String babyDes = "";

	int babySex = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_baby);

		((TextView) findViewById(R.id.center)).setText("宝宝信息");
		MobclickAgent.onEvent(this, ((TextView) findViewById(R.id.center))
				.getText().toString());
		
		((Button)findViewById(R.id.left)).setText("取消");
		((Button)findViewById(R.id.left)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

		((Button) findViewById(R.id.right)).setText("完成");
		((Button) findViewById(R.id.right)).setTextColor(Color
				.parseColor("#EE7C1C"));
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);

		findViewById(R.id.action0).setOnClickListener(this);
		findViewById(R.id.action1).setOnClickListener(this);
		findViewById(R.id.action2).setOnClickListener(this);
		findViewById(R.id.action3).setOnClickListener(this);
		findViewById(R.id.action4).setOnClickListener(this);
		findViewById(R.id.action5).setOnClickListener(this);

		((TextView) findViewById(R.id.value2)).setText("男宝宝/女宝宝");
	}

	Dialog mDialog = null;
	private File mPhotoFile;

	void showImagePicker() {
		mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(this);
		mDialog.findViewById(R.id.pic).setOnClickListener(this);
		mDialog.findViewById(R.id.cancel).setOnClickListener(this);
		mDialog.findViewById(R.id.dialog_layout).setOnClickListener(this);
		mDialog.findViewById(R.id.show).setOnClickListener(this);
		mDialog.findViewById(R.id.show).setVisibility(View.VISIBLE);
		mDialog.show();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			showMainView();
			break;

		case R.id.right:
			sendHttpRequest();
			break;

		case R.id.show: {
			mDialog.dismiss();
			mDialog = null;

			Intent intent = new Intent(this, SingleImageShowActivity.class);
			intent.putExtra("url", PreferencesUtils.getString(this, "headurl"));
			startActivity(intent);
		}
			break;

		case R.id.action0:
			showImagePicker();
			break;

		case R.id.cancel:
		case R.id.dialog_layout:
			mDialog.dismiss();
			mDialog = null;
			break;

		case R.id.camera:
			mDialog.dismiss();
			mDialog = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(intent, 4);
			}
			break;

		case R.id.pic:
			mDialog.dismiss();
			mDialog = null;
			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType("image/*");
			startActivityForResult(getAlbum, 3);
			break;

		case R.id.action1: {
			Intent intent = new Intent(this, TextInputActivity.class);
			intent.putExtra("title", "昵称");
			intent.putExtra("content", babyNick);
			startActivityForResult(intent, 10);
			break;
		}

		case R.id.action2: {
			Intent intent = new Intent(this, TextInputActivity.class);
			intent.putExtra("title", "姓名");
			intent.putExtra("content", babyName);
			startActivityForResult(intent, 11);
			break;
		}

		case R.id.action3:
			showSex();
			break;

		case R.id.action4: {
			final Calendar c = Calendar.getInstance();
			int mYear = c.get(Calendar.YEAR);
			int mMonth = c.get(Calendar.MONTH);
			int mDay = c.get(Calendar.DAY_OF_MONTH);
			new DatePickerDialog(this, new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker arg0, int arg1, int arg2,
						int arg3) {
					StringBuffer buffer = new StringBuffer();
					buffer.append(arg1);
					buffer.append("-");
					arg2++;
					if (arg2 < 10)
						buffer.append(0);
					buffer.append(arg2);
					buffer.append("-");
					if (arg3 < 10)
						buffer.append(0);
					buffer.append(arg3);

					babyBirth = buffer.toString();
					((TextView) findViewById(R.id.value3)).setText(babyBirth);
				}
			}, mYear, mMonth, mDay).show();
			break;
		}

		case R.id.action5: {
			Intent intent = new Intent(this, TextInputActivity.class);
			intent.putExtra("title", "特征说明");
			intent.putExtra("content", babyDes);
			startActivityForResult(intent, 12);
			break;
		}
		}
	}

	public void showSex() {
		final String[] items = { "男宝宝", "女宝宝", "取消" };
		new AlertDialog.Builder(this).setTitle("选择性别")
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which < 2) {
							babySex = which;
							((TextView) findViewById(R.id.value2))
									.setText(items[which]);
						}

						dialog.dismiss();
					}
				}).show();
	}

	@SuppressWarnings({ "deprecation" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if (requestCode == 10) {
				babyNick = data.getStringExtra("content");
				((TextView) findViewById(R.id.value0)).setText(babyNick);
				return;
			} else if (requestCode == 11) {
				babyName = data.getStringExtra("content");
				((TextView) findViewById(R.id.value1)).setText(babyName);
				return;
			} else if (requestCode == 12) {
				babyDes = data.getStringExtra("content");
				((TextView) findViewById(R.id.value4)).setText(babyDes);
				return;
			}

			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			((ImageView) findViewById(R.id.img)).setImageBitmap(bitmap);
			startPhotoZoom(Uri.fromFile(mPhotoFile));
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	private void sendHttpRequest() {
		if (babyName.length() == 0 || babyNick.length() == 0) {
			ToastUtil.showToastWithAlertPic("宝宝姓名&昵称不能为空");
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					showToast("宝宝设备绑定成功");
					showMainView();
					
					JSONObject obj = JSON.parseObject(getIntent().getStringExtra("info"));
					BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
							.getRemoteDevice(obj.getString("address"));
					localBluetoothDevice.connectGatt(AddBabyActivity.this, false, ((DemoApp)getApplicationContext()).mGattCallback);
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "relChild");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("deviceid", getIntent().getStringExtra("deviceid"));
		params.put("childid", "");
		params.put("childname", babyName);
		params.put("nickname", babyNick);
		params.put("sex", String.valueOf(babySex + 1));
		params.put("birth", babyBirth);
		params.put("description", babyDes);

		try {
			if (mPhotoFile != null)
				params.put("filename0", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}

}
